import { useEffect, useMemo, useState } from "react"
import { useCountDown } from 'ahooks'
import callFeedback from "@/components/common/modalFeedback"
import { BASE_PATH,API } from '@/config'
import { AutoCenter, Button, Grid } from "antd-mobile"
import { navigateTo, checkENV2, triggerAppShare, } from "@/utils"
import requewt from "@/utils/requewt"
import { Toast } from 'antd-mobile'
import { useGameV2 } from './hooks/useGame'
import GameResult from "@/components/common/modalFeedback/game.result";
import { ResultComp } from "../../prize"

const Puzzel = () => {
    const handler = {
        finish: async (status) => {
          const options = {
            method: `POST`,
            headers: {"Content-Type": "multipart/form-data"},
            body: {"status": status},
          }
          const resp = await requewt(API.game.finish, options);
          return resp
          // const m = 
          // const 
          // if (status === '2') {
          //   return  handleSuccess()
          // }

        },
        play: async () => {
          Toast.show({icon: 'loading', content: '加载中', duration: 0, maskClickable: false})
          const resp = await requewt(API.game.start,{method: 'post'});
          // alert(resp?.error_code);
          Toast.clear()
          if (resp?.error_code == 1002) {
            console.log("需要去分享")
            const c = callFeedback({
              // title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败`}} />,
              content: <GameResult 
                content={
                  <div className="result-modal">
                    <div className="result-modal-text" style={{marginTop: 30}} dangerouslySetInnerHTML={{__html: resp?.msg || `失败`}} />
              <Button key={`confirm`} onClick={async e => {
              const env = await checkENV2();
              if (env === `app`) await triggerAppShare()
              else if (env === `mini`) {
                Toast.show({content: `点击右上角「...」进行分享`})
              } else {
                Toast.show({content: `请在APP或小程序内打开`})
              }

              const resp = await requewt(API.user.share, {body: {source: 'game'}});
              if (resp?.error_code !== 0) return;
              // Toast.show({content: `分享成功`});
              // c.close();
            }} size="small" className="act-btn act-btn-primary">分享</Button>
            </div>
                }
              />
              
              ,
              // content: <ResultComp 
              // content={
              //   ,
              actions: [
                // <Button key={`confirm`} onClick={async e => {
                //   const env = await checkENV2();
                //   if (env === `app`) await triggerAppShare()
                //   else if (env === `mini`) {
                //     Toast.show({content: `点击右上角「...」进行分享`})
                //   } else {
                //     Toast.show({content: `请在APP或小程序内打开`})
                //   }
    
                //   const resp = await requewt(API.user.share);
                //   if (resp?.error_code !== 0) return;
                //   // Toast.show({content: `分享成功`});
                //   // c.close();
                // }} size="small" className="act-btn act-btn-primary">分享</Button>,
              ],
              closeOnAction: true,
              closeOnMaskClick: false,
            })
            return
          }
          console.log(resp);
          if (resp?.msg == "ok") {
            return resp
          }else{
            return Toast.show({content: `请求游戏失败`})
          }
        },
        start: async () => {
          //  else {
            
            
            // timer = setInterval(() => {
            //   updateTimer()
            // }, 1000)
            setTimeout(() => {
              
            //   App.run(Config,handler)
            }, 200)
        },
        sendEnd: ()=> {
          // console.log(window.phase, phase);
          if (window.phase === "playing") {
            au.current.pause();
            end();
          }
        }
      }
    const handlerFail = async () => {
      await handler.finish('3')
      
        const c = callFeedback({
            bodyClassName: 'result-modal act-feedback-modal',
            closeOnAction:false,
            hideClose:true,
        closeOnMaskClick: false,
            content: (<GameResult 
              content={<div className="result-modal">
              <div className="result-modal-icon">
                  <img src={`${BASE_PATH}/img/game/fail-icon.png`} />
                  
              </div>
              <div className="result-modal-text">很遗憾，拼图挑战失败</div>
              {/* <div className="result-modal-text2">挑战失败，分享可获得1次游戏机会</div> */}
              
          </div>}
            />),
            
            actions: <Grid columns={2} gap={20}>
              <Grid.Item>
              <Button key="home" className="act-btn" onClick={async e => {
                c.close()
                history.go(-1)
                
                  }}>返回首页</Button>
              </Grid.Item>
              <Grid.Item>

<Button key="share" className="act-btn" onClick={async e => {
                // location.reload()
                c.close()
                setTips('快速记忆拼图内容')
                handler.play().then((data) => {
                  init(`${BASE_PATH}/img/game/puzzle_1221_${data?.data?.puzzle}.jpg`).then((result) => {
                      if (!result) {
                          return Toast.show('获取图片失败')
                      }
                      setTargetDate(Date.now() + 50000)
                      setTips('拼图大比拼')
                  })
              })
                  }}>再次挑战</Button>
              </Grid.Item>
            </Grid>
        })
    }
    const handleSuccess = () => {
      
        setTargetDate(undefined)
        // const 
        handler.finish('2').then((result) => {
          if (result.error_code === 0) {
            const c = callFeedback({
              bodyClassName: 'result-modal act-feedback-modal',
              closeOnAction:false,
          closeOnMaskClick: false,
              content: (<div className="result-modal">
                  <div className="result-modal-icon">
                      <img src={`${BASE_PATH}/img/game/sucess-icon.png`} />
                      
                  </div>
                  <div className="result-modal-text">恭喜您，集齐拼图</div>
                  {/* <div className="result-modal-text2">您已完成拼图，可免费抽奖{result.data.remain_draw_num}次</div> */}
                  {
                    result.data?.draw_chance? <div className="result-modal-text2">获得1次抽奖机会</div> : null
                  }
                  
              </div>),
              hideClose:true,
              
              actions: [
                <Button key="gohome" className="act-btn" onClick={()=>{
                  c.close()
                  navigateTo('/landing')
              }}>返回首页</Button>,
              <Button key="share" className="act-btn" onClick={async e => {
                  c.close()
                  navigateTo(`/wheel`)
              }}>立即抽奖</Button>
              ]
          })
          }

        })
        
    }
    const [targetDate,setTargetDate] = useState()
    const [countdown] = useCountDown(
        
        {
            targetDate,
        onEnd() {
            setTimeout(() => {
              handlerFail()
            },500)
        }
    })
    const [tips, setTips] = useState('快速记忆拼图内容')
    // console.log(formattedRes,'form')
    const timer = useMemo(() => {
      const str = Math.round(countdown/1000).toString()
      let oneDigit,tenDigits
      if (str.length>1) {
        oneDigit = str.split('')[0]
        tenDigits = str.split('')[1]
      } else {
        oneDigit = '0'
        tenDigits = str
      }
      return {
        oneDigit,
        tenDigits
      }
    },[countdown])
    const {init, canvasRef, imgBoxRef} = useGameV2(12,{onSuccess:handleSuccess} )
        useEffect(() => {
            handler.play().then((data) => {
                init(`${BASE_PATH}/img/game/puzzle_1221_${data?.data?.puzzle}.jpg`).then((result) => {
                // init(`${BASE_PATH}/img/game/puzzle_1021_6.jpg`).then((result) => {
                    if (!result) {
                        return Toast.show('获取图片失败')
                    }
                    setTargetDate(Date.now() + 50000)
                    setTips('拼图大比拼')
                })
            })
            
        }, [])
        useEffect(() => {
            if (countdown <= 0) {
                imgBoxRef.current.classList.add('disabled')
            } else {
                imgBoxRef.current.classList.remove('disabled')
            }
        },[countdown])
    useEffect(() => {
        // setTargetDate(Date.now() + 3000000)
        // handlerFail()
       
    },[])
    
    return (
        <div className="puzzle-game-container">
            
            <div className="game-top">
            <div className="game-tips">
                {tips}
            </div>
            <div className="game-time">
                {/* 剩余时间：{Math.round(countdown / 1000)}s */}
                <img 
                  src={`${BASE_PATH}/img/game/game-time.png`}
                />
                <div className="time-num">
                  <Grid columns={2} gap={4}>
                    <Grid.Item>{timer.oneDigit}</Grid.Item>
                    <Grid.Item>{timer.tenDigits}</Grid.Item>
                  </Grid>
                </div>
            </div>
            
            </div>
            {/* <div>
              <AutoCenter>
                <p style={{color:'#333',fontSize:'14px'}}>{tips}</p>
              </AutoCenter>
            </div> */}
            <div id="game">
            <canvas id="canvas" ref={canvasRef}>
                cannot support canvas
            </canvas>
            <div id="grid-imgs" ref={imgBoxRef}>
        </div>
        <div className="game-title">
        每日可挑战不同样式拼图
            </div>
        
        </div>
            {/* <PuzzleGame times={Math.round(countdown/1000)} onSuccess={handleSuccess} /> */}
        </div>
    )
}

export default Puzzel
